package com.evol.controller;

import com.evol.domain.AjaxResult;
import com.evol.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 *
 * @author EvOL
 * @description
 * @date 2024-06-03 09:17
 **/
@Controller
public class ProxyController extends BaseController{
    @Value("${evol.tls_mode}")
    private boolean tls_mode;
    @Value("${evol.dashboard_addr}")
    private String dashboard_addr;
    @Value("${evol.dashboard_port}")
    private Integer dashboard_port;
    @Value("${evol.dashboard_user}")
    private String dashboard_user;
    @Value("${evol.dashboard_pwd}")
    private String dashboard_pwd;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping({"/proxy/api/{serverApi}","/proxy/api/{serverproxyApi}/{serverApi}"})
    @ResponseBody
    public AjaxResult proxyRequest(@PathVariable(required = false) String serverproxyApi, @PathVariable String serverApi) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        headers.setBasicAuth(dashboard_user, dashboard_pwd);

        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);

        String http="http";
        if (tls_mode){
            http="https";
        }
        String url=http+"://"+dashboard_addr+":"+dashboard_port+"/api";
        String uri="/"+ serverApi;
        if(StringUtils.isNotEmpty(serverproxyApi)){
            uri="/"+ serverproxyApi+uri;
        }
        url=url+uri;

        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    String.class);
            if(responseEntity.getStatusCode()==HttpStatus.OK){
                String body=responseEntity.getBody();
                return AjaxResult.successUni("Proxy to "+url+" success",body);
            }else{
                return AjaxResult.error("Proxy to "+url+" error");
            }
        }catch (Exception es){
            return AjaxResult.error("Proxy Connect Timeout "+es.toString());
        }
    }
}
